package model;

import java.util.ArrayList;

/**
 * 
 * @author Martin Mohr Pedersen
 */
public class ItemCollection {

	private static ItemCollection instance;

	private ArrayList<Item> items;

	private ItemCollection() {
		items = new ArrayList<Item>();
	}

	public static ItemCollection getInstance() {
		if (instance == null) {
			instance = new ItemCollection();
		}

		return instance;
	}

	/**
	 * Adds item to collection.
	 * 
	 * @param item
	 */
	public void addItem(Item item) throws DuplicateItemIdentifierException {

		Item existingItem = getItem(item.getItemNo());
		if (getItem(item.getItemNo()) == null) {
			items.add(item);
		} else {
			throw new DuplicateItemIdentifierException();
		}
	}

	/**
	 * Returns array of all items.
	 * 
	 * @return non-referrence array of all items.
	 */
	public Item[] getItems() {
		return items.toArray(new Item[items.size()]);

	}

	/**
	 * Removes item from collection.
	 * 
	 * @param item
	 *            object to remove.
	 */
	public void removeItem(Item item) {
		items.remove(item);
	}

	/**
	 * Removes item with specified itemNo.
	 * 
	 * @param itemNo
	 */
	public void removeItem(String itemNo) {
		Item item = getItem(itemNo);
		if (item != null) {
			removeItem(item);
		}
	}

	/**
	 * Returns item from collection by itemNo comparison.
	 * 
	 * @param itemNo
	 *            itemNo to match against.
	 * @return Matching item or null if none.
	 */
	public Item getItem(String itemNo) {
		int index = 0;
		Item currentItem = null;
		while (index < items.size()) {
			currentItem = items.get(index);
			if (currentItem.getItemNo().equals(itemNo)) {
				return currentItem;
			}
			index++;
		}

		return null;
	}

}
